package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component

public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    //Around环绕通知，可以在目标方法执行前后织入增强内容
    @Around("@annotation(com.itheima.anno.Log)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 执行目标方法
        Object result = joinPoint.proceed();
        // 计算耗时
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        // 构建日志实体
        OperateLog olog = new OperateLog();
        // 获取操作人ID
        olog.setOperateEmpId(getCurrentUserId()); // 这里需要你根据实际情况获取当前用户ID
        // 获取操作时间
        olog.setOperateTime(LocalDateTime.now());
        // 获取目标方法的签名对象
        olog.setClassName(joinPoint.getTarget().getClass().getName());
        // 获取方法签名
        olog.setMethodName(joinPoint.getSignature().getName());
        // 获取方法参数
        olog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        // 获取方法返回值
        String returnValue = result != null ? result.toString() : "void";
        if (returnValue.length() > 8000) {
            returnValue = returnValue.substring(0, 8000);
        }
        olog.setReturnValue(returnValue);
        // 获取方法执行耗时
        olog.setCostTime(costTime);

        // 保存日志
        log.info("记录操作日志: {}", olog);
        operateLogMapper.insert(olog);

        return result;
    }

    // 获取当前用户ID用于记录操作日志
    private Integer getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}